package com.stu.init;

import com.stu.pojo.Pro;
import com.stu.pojo.Product;
import com.stu.service.EsProService;
import com.stu.service.IProductService;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class EsProInitService {

    @Autowired
    private EsProService esProService;

    @Autowired
    private IProductService productService;

    @PostConstruct
    public void initEsData() {
        long count = esProService.count();
        if (count > 0) {
            System.out.println("Elasticsearch 中已有数据，无需初始化。现有数据条数：" + count);
            return;
//            esProService.deleteAll();
//            System.out.println("Elasticsearch 商品数据已清空。");
        }

        System.out.println("开始初始化 Elasticsearch 数据...");
        var productList = productService.getAll();
        for (Product product : productList) {
            Pro pro = new Pro();
            pro.setId(product.getProductId());
            pro.setProductName(product.getProductName());
            pro.setProductType(product.getProductType());
            pro.setProductBrand(product.getProductBrand());
            pro.setProductPrice(product.getProductPrice());
            pro.setProductColor(product.getProductColor());
            pro.setProductSize(product.getProductSize());
            pro.setProductMainImg(product.getProductMainImg());
            pro.setProductCount(product.getProductCount());
            pro.setProductPoint(product.getProductPoint());
            pro.setProductArea(product.getProductArea());
            pro.setProductSold(product.getProductSold());
            pro.setXx(product.getXx());
            pro.setYy(product.getYy());
            pro.setProductVersion(product.getProductVersion());
            pro.setProductStatus(product.getProductStatus());
            esProService.save(pro);
        }

        System.out.println("Elasticsearch 商品数据初始化完成，共导入：" + productList.size() + " 条记录");
    }
}
